var preSelectDiv;
var preSelectedDiv;
 var filterMap = {};
 
function newShaixuan() {
	var width = document.body.clientWidth / 3;
	var height = document.body.clientHeight / 4;
	jQuery('#shaixuan').lightbox_me({
				modalCSS : {
					top : height,
					left : width
				}
			});
}

function closeShaixuan() {
	$("#filterValue").val("");
	$("#addedFilters").html("");
	jQuery('#shaixuan').trigger('close');
}

function selectIndexshaixuan(o) {
	$(preSelectDiv).css("background", "#fff");
	preSelectDiv = o;
	$(o).css("background", "#009cff");
}

function quickMoveshaixuan(o) {
	selectIndexshaixuan(o);
	moveIndexshaixuan();
};

function moveIndexshaixuan() {
	if (!preSelectDiv) {
		alert("请先选择指标");
		return;
	}
	var val = $.trim($("#filterValue").val());
	if (val.length === 0) {
		alert("请输入过滤条件");
		return;
	}
	if (!/^-?\d+(\.\d+)?$/.test(val)) {
		alert("输入的过滤条件格式错误");
		return;
	}
	if (!/^-?\d{1,15}(\.\d+)?$/.test(val)) {
		alert("过滤条件最多只能输入15位整数");
		return;
	}
	var size = $("#addedFilters").children().size();
	if (size >= 3) {
		alert("只能选择3个过滤条件");
		return;
	}
	var selectedId = "~" + preSelectDiv.id + "@#"+$("input[name=comp]:checked").attr("id")+"$"+val;
	var div = $("<div id='"+selectedId+"' style='cursor:pointer;'>"
			+ "#" + $(preSelectDiv).html() + "#"
			+ $("input[name=comp]:checked").val() + val + "</div>");
	$("#addedFilters").append(div);
	var filterArr = filterMap[selectedId];
	if (filterArr === undefined) {
		filterArr = [];
		filterMap[selectedId] = filterArr;
	}
	filterArr.push($("input[name=comp]:checked").val() + val);
	div.dblclick(moveSelectedIndexshaixuan);
	div.click(function() {
				$(preSelectedDiv).css("background", "#fff");
				$(this).css("background", "#009cff");
				preSelectedDiv = this;
			});
}

function moveSelectedIndexshaixuan() {
	if (!preSelectedDiv) {
		alert("请选择要删除的筛选条件");
		return;
	}
	var filterArr = filterMap[preSelectedDiv.id];
	if (filterArr) {
		for (var i = 0; i < filterArr.length; i++) {
			if ($(preSelectedDiv).text().indexOf(filterArr[i]) >= 0) {
				filterArr.splice(i, 1);
				break;
			}
		}
	}
	if (filterArr.length === 0) {
		delete filterMap[preSelectedDiv.id];
	}
	$(preSelectedDiv).remove();
	preSelectedDiv = null;
}

function submitFiltershaixuan(){
	var clds = $("#addedFilters").children();
	if(clds.length === 0){
		alert("已选区不能为空");
		return ;
	}
	for(i = 0; i < clds.length; i++){
		var ids = clds[i].id;
		var id = ids.substring(ids.indexOf("~") + 2,ids.indexOf("@"));
		var opt = ids.substring(ids.indexOf("#") + 1,ids.indexOf("$"));
		var value = ids.substring(ids.indexOf("$")+1);
		submitshaixuan(id,opt,value);
	}
	$("#filterValue").val("");
	$("#addedFilters").html("");
	jQuery('#shaixuan').trigger('close');
}
